#coding:utf-8
import sys,os
sys.path.append("matchutils")
import json
import pickle
import random
from config import *

from sklearn import metrics
from sklearn.ensemble import GradientBoostingRegressor

class Vector(object): 
    def __init__(self):
        self.avg_intro_sim = 0.35
        self.keynum = 0
        self.keys = {}
        fname = dict_dir + '/keys.txt'
        f = open( fname, 'rb')
        for line in f:
            line = line.strip()
            if line == '': continue
            fields = line.split('\t')
            if len(fields) != 2: continue
            key, kid = fields
            kid = int(kid)
            if kid > self.keynum:
               self.keynum = kid 
            self.keys[key] = kid
        f.close()
        
    def parse(self, features):
        if not features: 
            return []
        if not isinstance(features, dict) :
            return []
        vector = {}
        for key,val in features.items():
            if key not in self.keys:
                continue

            if isinstance(val, float) :
                val = int(val*100)/100.0
            if val is None and key == 'intro_sim':
                val = self.avg_intro_sim
            if val is None:
                return None
            kid = self.keys[ key ]
            vector[kid] = val
        if not vector: return []
        v = []
        for i in range(self.keynum):
            idx = i + 1
            if idx in vector:
                v.append( vector[idx] )
            else:
                v.append( 0.0 )
        return v


class Predictor(object):
    def __init__(self, mod_fname):
        self._limit = 0.60
        self._gen = Vector()
        f = open( mod_fname, 'rb')
        self._model = pickle.load(f)
        f.close()
    def get_limit(self):
        return self._limit
    def predict(self, features ):
        if not features: return 0

        vec = self._gen.parse( features )
        if not vec:
            return 0
        labels = self._model.predict( [ vec ] )
        return labels[0]

gbrt_model = Predictor( dict_dir +  "/gbrt.video.model")

if __name__ == "__main__":
    #make_vectors()
    make_vectors(False)

